import path from "node:path";
import fs from "node:fs";

export function get_template(baseDir,template_file='template.html',js_replace='<!--app-js-->',css_replace='<!--app-css-->') {
    let clientDir = path.join(baseDir, "dist", "client","assets");
    let cssFiles = []
    let scriptFiles = []
    let templateFile=path.join(baseDir,"src","assets",template_file);
    let scriptTag=`<script type="module" crossorigin src="#"></script>`
    let linkTag=`<link rel="stylesheet" crossorigin href="#">`
    try {
        if (!fs.existsSync(baseDir)) {
            throw new Error(`baseDir does not exist: ${baseDir}`);
        }
        if (!fs.existsSync(templateFile)) {
            throw new Error(`templateFile does not exist: ${templateFile}`);
        }
        //遍历baseDir目录文件
        for (const file of fs.readdirSync(clientDir)) {
            console.log("get file >> ",file)
            if(path.extname(file) === ".js") {
                scriptFiles.push(path.join("/assets", file))
            }
            if(path.extname(file) === ".css") {
                cssFiles.push(path.join("/assets", file))
            }
        }
        // console.log("get cssFiles >> ",cssFiles)
        // console.log("get scriptFiles >> ",scriptFiles)
        let template=fs.readFileSync(templateFile,"utf8")
        // console.log("get template >> ",template)
        let css_html=''
        for (const element of cssFiles) {
            if(css_html){
                css_html+='\r\n'
            }
            css_html+=linkTag.replace("#",element)
        }
        let js_html=''
        for (const element of scriptFiles) {
            if(js_html){
                js_html+='\r\n'
            }
            js_html+=scriptTag.replace("#",element)
        }
        template = template.replace(css_replace,css_html)
        template = template.replace(js_replace,js_html)
        return template
    } catch (e) {
        console.log(e)
    }
}